<?php
/**
 * 功能：后台菜单控制器
 * 作者：魏安来
 * 日期：2017/01/09
 */

namespace app\index\controller;
use app\index\model\User as UserModel;
use app\index\model\AuthGroup;
use think\Db;

class User extends Base {

	/*用户列表*/
	public function index() {
		//调用左侧菜单
		$menuController = new Menu();
		$menuController->sidebar();
		//查询所有角色
		$userModel = new UserModel();
		$allUser = $userModel->getAllUser();
		$auth = new Auth();
		/*查找角色并添加到结果集*/
        foreach($allUser as $k=>$v) {
            $role[$k] = $v;
            $roleArr = $auth->getGroups($v['id']);
            foreach($roleArr as $val) {
                $allUser[$k]['role'] = $val;
            }
        }
		$this->assign('allUser', $allUser);
		return $this->fetch();
	}

	/*添加用户*/
	public function add() {
		//查询所有角色
		$roleModel = new AuthGroup();
		$allRole = $roleModel->getAllRole();
		$this->assign('allRole', $allRole);
		if (request()->isAjax()) {
			//接收数据
			$data = input('post.');
			if (!isset($data['status'])) {
				$data['status'] = 0;
			} else {
				$data['status'] = 1;
			}
			unset($data['role']);
			//定义验证规则
            $rule = [
				'username' => 'require|min:2|unique:user,username='.$data['username'],
				'password' => 'require|confirm:password',
				're_password' => 'require|min:6'
            ];

            //定义错误提示信息
            $message = [
                'username.require' => '用户名称不能为空',
				'username.min' => '用户名称不能少于2个字符',
				'username.unique' => '用户名称已存在',
				'password.require' => '密码不能为空',
				'password.min' => '密码不能少于6位',
				're_password.require' => '确认密码不能为空',
				're_password.confirm' => '两次输入的密码不一致',
            ];
			$validate = new \think\Validate($rule, $message);
            $result = $validate->check($data);
            unset($data['re_password']);
			if ($result) {
				//写入数据库
				$data['password'] = sha1($data['password']);
				$lastId = db('user')->insertGetId($data);
				if ($lastId) {
					$insertData = [
						'uid' => $lastId,
						'group_id' => input('role')
					];
					$result = db('auth_group_access')->insert($insertData);
					if ($result) {
						return 'succ';
					} else {
						return 'error';
					}
					
				} else {
					return 'error';
				}
			} else {
				return $validate->getError();
			}
		}
		return $this->fetch();
	}

	/*编辑用户*/
	public function edit() {
		//查询所有角色
		$roleModel = new AuthGroup();
		$allRole = $roleModel->getAllRole();
		$this->assign('allRole', $allRole);
		//用户id
		$id = request()->param('id');
		//接收要编辑的权限规则id
		$id = request()->param('id');
		//查找用户信息
		$result=Db::name('user')->where('id', $id)->find();
		//根据用户id查询用户信息
		$user = new UserModel();
		$userInfo = $user->getUserInfo($id);
		$group_id = $user->getGroupId($id);
		$this->assign('id',$id);
		$this->assign('group_id',$group_id);
		$this->assign('userInfo',$userInfo);
		if (request()->isAjax()) {
			//接收数据
			$data = input('post.');
			if (!isset($data['status'])) {
				$data['status'] = 0;
			} else {
				$data['status'] = 1;
			}
			unset($data['role']);
			//如果没有修改用户名就不验证用户名是否已存在
			if (trim($data['username']) == trim($result['username'])) {
				if ($data['password'] == '') {
					//定义验证规则
		            $rule = [
						'username' => 'require|min:2'
		            ];
				} else {
					//定义验证规则
		            $rule = [
						'username' => 'require|min:2',
						'password' => 'require|confirm:password',
						're_password' => 'require|min:6'
		            ];
				}

	            //定义错误提示信息
	            $message = [
	                'username.require' => '用户名称不能为空',
					'username.min' => '用户名称不能少于2个字符',
					'password.require' => '密码不能为空',
					'password.min' => '密码不能少于6位',
					're_password.require' => '确认密码不能为空',
					're_password.confirm' => '两次输入的密码不一致',
	            ];
			} else {
				if ($data['password'] == '') {
					//定义验证规则
	           		$rule = [
						'username' => 'require|min:2|unique:user,username='.$data['username'],
		            ];
				} else {
					//定义验证规则
		            $rule = [
						'username' => 'require|min:2|unique:user,username='.$data['username'],
						'password' => 'require|confirm:password',
						're_password' => 'require|min:6'
		            ];
				}
				
	            //定义错误提示信息
	            $message = [
	                'username.require' => '用户名称不能为空',
					'username.min' => '用户名称不能少于2个字符',
					'username.unique' => '用户名称已存在',
					'password.require' => '密码不能为空',
					'password.min' => '密码不能少于6位',
					're_password.require' => '确认密码不能为空',
					're_password.confirm' => '两次输入的密码不一致',
	            ];
			}
			$validate = new \think\Validate($rule, $message);
			$result = $validate->check($data);
			if($result) {
				if ($data['password'] != '') {
					$data['password'] = sha1($data['password']);
				} else {
					unset($data['password']);
				}
				unset($data['re_password']);
				unset($data['id']);
				$affected = $user->updataOneData($id, $data);
				if (!$affected) {
					if (input('role') != $group_id) {
						$affected = true;
					}
				}
				if ($affected) {
					if (input('role') != $group_id) {
						$updateData = [
						'group_id' => input('role')
						];
						$affect = db('auth_group_access')->where('uid',$id)->update($updateData);
						if ($affect) {
							return 'succ';
						} else {
							return 'error';
						}
					} else {
						if ($affected) {
							return 'succ';
						} else {
							return 'error';
						}
					}
				} else {
					return 'error';
				}
			} else {
				return $this->getError();
			}
		}
		return $this->fetch();
	}

	/*用户删除*/
	public function delete() {
		$id = request()->param('id');
		$userModel = new UserModel();
		$affected = $userModel->deleteOneUser($id);
		if ($affected) {
			return 'succ';
		} else {
			return 'error';
		}
	}

}

?>